let currentNovelId = null;
let currentChapterId = null;
let isNewChapter = false;
let currentVolumeName = '';

$(document).ready(function() {
    // 从window.editorData获取数据（由JSP传递）
    if (window.editorData) {
        currentNovelId = window.editorData.novelId;
        currentChapterId = window.editorData.chapterId;
        isNewChapter = window.editorData.isNewChapter;
        currentVolumeName = window.editorData.volumeName;
    } else {
        // 兼容原有的URL参数方式
        const urlParams = new URLSearchParams(window.location.search);
        currentNovelId = urlParams.get('novelId');
        currentChapterId = urlParams.get('chapterId');
        isNewChapter = urlParams.get('new') === 'true';
        currentVolumeName = decodeURIComponent(urlParams.get('volumeName') || '');
    }
    
    if (!currentNovelId) {
        showError('缺少小说ID参数');
        return;
    }
    
    // 绑定内容变化事件
    $('#chapterContent').on('input', updateWordCount);
    
    // 初始化字数统计
    updateWordCount();
    
    // 页面离开前提醒保存
    window.addEventListener('beforeunload', function(e) {
        if (hasUnsavedChanges()) {
            e.preventDefault();
            e.returnValue = '您有未保存的更改，确定要离开吗？';
        }
    });
});

/**
 * 加载小说信息
 */
function loadNovelInfo() {
    $.ajax({
        url: '/demo1_war_exploded/API/Author/novelDetail',
        type: 'GET',
        data: { novelId: currentNovelId },
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                $('#novelTitle').text(`《${response.data.novel_name}》`);
            }
        },
        error: function() {
            $('#novelTitle').text('未知小说');
        }
    });
}

/**
 * 加载章节内容
 */
function loadChapterContent() {
    $.ajax({
        url: '/demo1_war_exploded/API/Author/chapterDetail',
        type: 'GET',
        data: { chapterId: currentChapterId },
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                const chapter = response.data;
                $('#chapterTitle').val(chapter.chapter_title);
                $('#chapterContent').val(chapter.content);
                // 设置分卷信息
                if (chapter.volume_name) {
                    $('#volumeName').val(chapter.volume_name);
                }
                updateWordCount();
            } else {
                showError('加载章节失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 保存草稿
 */
function saveChapterDraft() {
    saveChapter('草稿');
}

/**
 * 发布章节
 */
function publishChapter() {
    if (!$('#chapterTitle').val().trim()) {
        showError('请输入章节标题');
        return;
    }
    
    if (!$('#chapterContent').val().trim()) {
        showError('请输入章节内容');
        return;
    }
    
    saveChapter('已发布');
}

/**
 * 保存章节
 */
function saveChapter(status) {
    const data = {
        novelId: currentNovelId,
        chapterTitle: $('#chapterTitle').val().trim(),
        content: $('#chapterContent').val().trim(),
        volumeName: $('#volumeName').val().trim(), // 添加分卷信息
        status: status
    };
    
    let url, action;
    if (currentChapterId && !isNewChapter) {
        // 更新现有章节
        data.chapterId = currentChapterId;
        url = '/demo1_war_exploded/API/Chapter';
        data.action = 'update';
    } else {
        // 创建新章节
        url = '/demo1_war_exploded/API/Chapter';
        data.action = 'create';
    }
    
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(response) {
            if (response.code === 200) {
                showSuccess('章节发布成功');
                
                // 如果是新章节，更新章节ID
                if (isNewChapter || !currentChapterId) {
                    currentChapterId = response.data.chapterId;
                    isNewChapter = false;
                    // 更新URL
                    const volumeName = $('#volumeName').val().trim();
                    const newUrl = `${window.location.pathname}?novelId=${currentNovelId}&chapterId=${currentChapterId}&volumeName=${encodeURIComponent(volumeName)}`;
                    window.history.replaceState({}, '', newUrl);
                }
            } else {
                showError(response.msg || '保存失败');
            }
        },
        error: function() {
            showError('网络错误，请稍后重试');
        }
    });
}

/**
 * 自动保存
 */
function autoSave() {
    if (hasUnsavedChanges() && $('#chapterTitle').val().trim() && $('#chapterContent').val().trim()) {
        saveChapter('草稿');
    }
}

/**
 * 检查是否有未保存的更改
 */
function hasUnsavedChanges() {
    // 检测标题、内容和分卷信息是否有变化
    return $('#chapterTitle').val().trim() || $('#chapterContent').val().trim() || $('#volumeName').val().trim();
}

/**
 * 更新字数统计
 */
function updateWordCount() {
    const content = $('#chapterContent').val();
    const wordCount = content.length;
    $('#wordCount').text(`字数: ${wordCount}`);
}

/**
 * 返回章节管理
 */
function goBack() {
    if (hasUnsavedChanges()) {
        if (confirm('您有未保存的更改，确定要离开吗？')) {
            window.location.href = `/demo1_war_exploded/MainPage/functionPage/authorWorkspace.jsp?tab=chapters&novelId=${currentNovelId}`;
        }
    } else {
        window.location.href = `/demo1_war_exploded/MainPage/functionPage/authorWorkspace.jsp?tab=chapters&novelId=${currentNovelId}`;
    }
}

/**
 * 显示成功消息
 */
function showSuccess(message) {
    showMessage(message, 'success');
}

/**
 * 显示错误消息
 */
function showError(message) {
    showMessage(message, 'danger');
}

/**
 * 显示消息
 */
function showMessage(message, type) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('#messageContainer').html(alertHtml);
    
    // 3秒后自动消失
    setTimeout(() => {
        $('.alert').alert('close');
    }, 3000);
}